import axios from 'axios';
import CryptoJS from 'crypto-js';
import { sysTime } from '@/utils/index';
// import router from '@/router/index'

const request = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
});

// 请求拦截
request.interceptors.request.use(
  function (config) {
    //请求头添加签名
    config.headers['s-i-g'] = CryptoJS.MD5(import.meta.env.VITE_SIG + sysTime()).toString();
    const token = localStorage.getItem('TOKEN');
    if (token) {
      config.headers['Authorization'] = token;
    }
    return config;
  },
  function (error) {
    return Promise.reject(error);
  },
);

// 添加响应拦截
request.interceptors.response.use(
  function (response) {
    const { code, msg } = response.data;
    if (code === '50003') {
      ElMessage({
        message: msg,
        type: 'warning',
      });
      localStorage.removeItem('TOKEN');
      // router.push('/login')
      return Promise.reject();
    }
    return response;
  },
  function (error) {
    return Promise.reject(error);
  },
);
/**
 * http请求
 * @returns
 * url: string 请求地址
 * params: unknown 请求参数
 * config: object 请求配置
 * get: 请求
 * post: 请求
 */
const http = {
  get(url, params, config) {
    return new Promise((resolve, reject) => {
      request
        .get(url, { params, ...config })
        .then((res) => {
          resolve(res.data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
  post(url, data, config) {
    return new Promise((resolve, reject) => {
      request
        .post(url, data, config)
        .then((res) => {
          resolve(res.data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
};

export default http;
